//
//  Location.m
//  sztdcs
//
//  Created by mokai on 14/12/27.
//  Copyright (c) 2014年 mokai. All rights reserved.
//

#import "Location.h"

@interface Location()
@property(nonatomic,retain) CLLocationManager *locMg;
@property (nonatomic,retain) CLGeocoder *geocoder;
@property(nonatomic) BOOL isRepeat;
@end

@implementation Location

@synthesize delegate;

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.locMg = [[CLLocationManager alloc]init];
        self.locMg.desiredAccuracy=kCLLocationAccuracyBest;
        
        self.locMg.delegate = self;
    }
    return self;
}

- (void)dealloc{
    [self stop];
    
}

/**
 *  停止定位
 */

-(void)stop{
    [_locMg stopUpdatingLocation];
}

/**
 *  开始定位
 */
-(void)start:(BOOL)isRepeat {
    self.isRepeat = isRepeat;
    switch (CLLocationManager.authorizationStatus) {
        case kCLAuthorizationStatusNotDetermined:
            if ([UIDevice currentDevice].systemVersion.floatValue>=8.0) {//兼容iOS8,必须代码请求授权
                [self.locMg requestAlwaysAuthorization];
                break;
            }
        case kCLAuthorizationStatusAuthorizedAlways:
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            [self.locMg startUpdatingLocation];//开启定位
            break;
        default:{
            if([UIDevice currentDevice].systemVersion.intValue >= 8){
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@""
                                                                   message:NSLocalizedString(@"定位访问未开启,请前往开启" , @"") delegate:self cancelButtonTitle:NSLocalizedString(@"返回"  , @"") otherButtonTitles:NSLocalizedString(@"去开启" , @""), nil];
                [alertView show];
            }else{
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@""
                                                                   message:NSLocalizedString(@"定位访问未开启,请前往 设置->隐私->定位服务 中开启" , @"") delegate:self cancelButtonTitle:NSLocalizedString(@"好"  , @"") otherButtonTitles: nil];
                [alertView show];
            }
        }
            break;
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://返回
            if (self.delegate && [delegate respondsToSelector:@selector(locationFail:)]) {
                [self.delegate locationFail:self];
            }
            break;
        default://前往设置
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            break;
    }
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status==kCLAuthorizationStatusAuthorized || kCLAuthorizationStatusAuthorizedWhenInUse==status) {
        [_locMg startUpdatingLocation];
    }else if(status==kCLAuthorizationStatusNotDetermined){
        if ([_locMg respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locMg requestAlwaysAuthorization];
        }
    }
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{
    CLLocation* location = [locations lastObject];
    NSDate* eventDate = location.timestamp;
    NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
    NSLog(@"latitude %+.6f, longitude %+.6f\n",
          location.coordinate.latitude,
          location.coordinate.longitude);
    if (abs(howRecent) < 15.0) {
        if (self.delegate) {
            [self.delegate location:self longitude:location.coordinate.longitude latitude:location.coordinate.latitude];
            //有重写则自动反编码
            if ([self.delegate respondsToSelector:@selector(location:address:)]) {
                [self geocodeLocation:location];
            }
            if (!self.isRepeat) {
                [self stop];
            }
        }
    }
}

//反编码
- (void)geocodeLocation:(CLLocation*)location
{
    if (!_geocoder)
        _geocoder = [[CLGeocoder alloc] init];
    [_geocoder reverseGeocodeLocation:location completionHandler:
     ^(NSArray* placemarks, NSError* error){
         if ([placemarks count] > 0)
         {
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             NSLog(@"当前位置:%@",placemark.addressDictionary);
             [self.delegate location:self address:placemark];
         }
     }];
}

@end
